package security;

import javax.el.ELContext;
import javax.faces.application.ProjectStage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import presentation.view_helpers.UserBean;

public class AuthenticationPhaseListener implements PhaseListener {

	/**
	 * JSF-Phase Listener used to redirect a user to the login page, if 
	 * he is not yet authenticated
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = LoggerFactory.getLogger(AuthenticationPhaseListener.class);
	private static final String LOGIN_PAGE = "/login.xhtml";

	public void afterPhase(PhaseEvent pe) {
		FacesContext fctx = FacesContext.getCurrentInstance();
		ELContext elctx = fctx.getELContext();
		UserBean user = (UserBean)elctx.getELResolver().getValue(elctx, null, "userBean");
		if ((user == null || user.getLoggedOnUser() == null) && (!fctx.getViewRoot().getViewId().equals(LOGIN_PAGE)) && (fctx.getApplication().getProjectStage()!=ProjectStage.Development)) {
			fctx.getApplication().getNavigationHandler().handleNavigation(fctx, null, LOGIN_PAGE);
		}
	}

	public void beforePhase(PhaseEvent pe) {
	}

	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
